<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const route = useRouter();
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Delete, Files, Plus, Connection, Document, EditPen } from '@element-plus/icons-vue'	//导入Search图标
import { treespage, treesexport, resourceDelete } from '@/utils/api.js'


// 优化更新
import haForm from '../common/ha-form.vue';

const haf = ref(null);
const multipleSelection = ref([]);
// 事件
const delItem = (item) => {
    ElMessageBox.confirm(
        '确定要删除这条数据吗?',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            resourceDelete({
                resourceType: "tree",
                ids: item
            }).then((res) => {
                if (res.code == '200') {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getAnimalsPage();
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.msg,
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}



const exportAnis = async () => {
    let params = {
        "areaId": usermsg.areaId,
        "level": [level.value],
        "keywords": keywords.value
    }

    let res = await treesexport(params)

    // 解析文件名
    const str = res.headers['content-disposition'].split(';')[1].split('=')[1];
    const filename = decodeURIComponent(str);
    // 用blob存储二进制文件
    const blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8', // 设置文件类型 pdf是application/pdf，word是application/vnd.openxmlformats-officedocument.wordprocessingml.document，其他类型可以百度一下
    });
    // 创建一个临时的url指向blob对象
    const objectUrl = window.URL.createObjectURL(blob);
    // 创建url之后可以模拟对此文件对象的一系列操作，例如：预览、下载
    const a = document.createElement('a');
    a.setAttribute('href', objectUrl);
    a.setAttribute('download', filename);
    a.click();
    // 5.释放这个临时的对象url
    window.URL.revokeObjectURL(objectUrl);
}

// 分页 B
const pageSize = ref(10);
const pageNum = ref(1);
const totalElements = ref(100);
const currentPage = ref(1);

const handleCurrentChange = (val) => {
    pageNum.value = val;
    getAnimalsPage();
};

const resp = () => {
    pageNum.value = 1;
    currentPage.value = 1;
    getAnimalsPage();
}


const handleSelectionSelectAll = (val) => {
    let arr = []
    val.forEach(e => {
        arr.push(e.id)
    })
    multipleSelection.value = arr;
}

const handleSelectionSelect = (val) => {
    let arr = []
    val.forEach(e => {
        arr.push(e.id)
    })
    multipleSelection.value = arr;
}

// 分页 E
const godetails = (data) => {
    let otws = {
        "pageSize": pageSize.value,
        "pageNum": pageNum.value,
        "keywords": keywords.value,
        "level": level.value,
        "currentPage": currentPage.value
    }
    window.sessionStorage.setItem('otws', JSON.stringify(otws));
    route.push({ path: '/otwss/details', query: { id: data.id } });
};


const level = ref("");
const keywords = ref("");
const options = ref([
    {
        value: '国家一级',
        label: '国家一级',
    },
    {
        value: '国家二级',
        label: '国家二级',
    },
    {
        value: '国家三级',
        label: '国家三级',
    },
]);

const list = ref([]);

const getAnimalsPage = async () => {
    let res = await treespage(usermsg.areaId, level.value, keywords.value, pageNum.value, pageSize.value)
    if (res.code == '200') {
        list.value = res.data.content;
        totalElements.value = res.data.totalElements;

        // 优化更新
        multipleSelection.value = []
    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
        list.value = []
    }
};
let usermsg = '';
onMounted(() => {
    usermsg = window.sessionStorage.getItem('usermsg');
    if (usermsg == undefined) {
        alert('您无权查看该网站，请登录后才能正常使用')
    } else {
        usermsg = JSON.parse(usermsg);
    };

    if (window.sessionStorage.getItem('otws') != null) {
        let data = JSON.parse(window.sessionStorage.getItem('otws'));
        pageSize.value = data.pageSize;
        pageNum.value = data.pageNum;
        level.value = data.level;
        keywords.value = data.keywords;
        currentPage.value = data.currentPage;
        getAnimalsPage();
        window.sessionStorage.removeItem('otws')
    } else {
        getAnimalsPage();
    }

})
</script>
<template>
    <div>
        <div class="ha-title" style="margin-bottom: 16px;">
            <div>
                <span>古树名木</span>
            </div>
            <!-- 优化更新 -->
            <div>
                <el-button :icon="Delete" @click="delItem(multipleSelection)" plain>删除({{ multipleSelection.length
                    }})</el-button>
                <el-button :icon="Files" @click="exportAnis" plain>导出</el-button>
                <el-button :icon="Plus" plain @click.stop="haf.openform('', '新增', 'tree', optionObj)">新增物种</el-button>
            </div>
        </div>
        <el-row :gutter="10">
            <el-col :span="3">
                <el-select v-model="level" class="m-2" @change="resp()" clearable placeholder="选择古树等级" size="large">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-col>
            <el-col :span="17"></el-col>
            <el-col :span="4">
                <el-input v-model="keywords" placeholder="搜索物种" size="large" class="input-with-select">
                    <template #append>
                        <el-button @click.stop="resp()" :icon="Search" />
                    </template>
                </el-input>
            </el-col>

        </el-row>
        <div style="height: 16px;"></div>

        <el-table :data="list" @select-all="handleSelectionSelectAll" @select="handleSelectionSelect"
            style="width: 100%;margin-top: 16px;height: calc(100% - 180px);"
            :header-cell-style="{ 'color': '#333', 'line-height': '40px' }">
            <el-table-column type="selection" width="35" />
            <el-table-column label="物种" width="180">
                <template #default="scope">
                    <div class="tb-sh">
                        <div>
                            <el-badge value="new" :hidden="!scope.row.isNew" class="item">
                                <img :src="scope.row.coverImage" alt="">
                            </el-badge>
                        </div>
                        <div>
                            <span :title="scope.row.zhong">{{
                                (scope.row.zhong && scope.row.zhong.length > 7) ?
                                    scope.row.zhong.slice(0, 7) + '...' :
                                    scope.row.zhong }}</span>
                            <br />
                            <span :title="scope.row.zhongLatinName">{{
                                (scope.row.zhongLatinName && scope.row.zhongLatinName.length > 16) ?
                                    scope.row.zhongLatinName.slice(0, 16) + '...' :
                                    scope.row.zhongLatinName }}</span>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="编号" prop="serialNumber" show-overflow-tooltip />
            <el-table-column label="树龄" prop="age" show-overflow-tooltip />


            <el-table-column label="保护等级">
                <template #default="scope">
                    <el-button v-if="scope.row.level == '国家二级'" class="rcc3">
                        {{ scope.row.level }}
                    </el-button>
                    <el-button v-else-if="scope.row.level == '国家一级'" class="rcc2">
                        {{ scope.row.level }}
                    </el-button>

                    <el-button v-else style="border: none;">
                        {{ scope.row.level }}
                    </el-button>
                </template>
            </el-table-column>


            <el-table-column label="操作" fixed="right" width="240">
                <!-- // 优化更新 -->
                <template #default="scope">
                    <el-button type="info" @click.stop="godetails(scope.row)" :icon="Document" plain size="small">
                        详情
                    </el-button>
                    <el-button type="info" plain :icon="EditPen"
                        @click.stop="haf.openform(scope.row, '修改', 'tree', optionObj)" size="small">
                        修改
                    </el-button>
                    <el-button type="info" plain :icon="Delete" @click.stop="delItem([scope.row.id])" size="small">
                        删除
                    </el-button>
                </template>
            </el-table-column>

        </el-table>

        <!-- 分页 B-->
        <div class="ml-page">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" size="small" background
                layout="total, prev, pager, next, jumper" :total="totalElements"
                @current-change="handleCurrentChange" />
        </div>
        <!-- 分页 E-->


        <!-- // 优化更新 -->
        <!-- 新增修改 -->
        <ha-form ref="haf" @refreshList="resp()" />
        <!-- 新增修改 -->

    </div>
</template>
<style scoped></style>